import { useState, useEffect } from 'react'
import MyHeader from './components/MyHeader'
import MyFooter from './components/MyFooter'
import GoodsItem from './components/GoodsItem'
import './App.scss'

const LIST = '@LIST@'

// 建议放到函数外面即可
export default function App() {
  const [list, setList] = useState([])

  const changeStatus = (id) => {
    setList(
      list.map((item) => {
        if (item.id === id) {
          return {
            ...item,
            goods_state: !item.goods_state,
          }
        } else {
          return item
        }
      })
    )
  }
  const changeAllStatus = (status) => {
    // !#3. 父组件根据传递过来参数做相应的操作
    setList(
      list.map((item) => {
        return {
          ...item,
          goods_state: status,
        }
      })
    )
  }

  // !#1 准备一个修改数据的方法
  const changeCount = (id, count) => {
    // !#3 根据接收到实参做相应的操作
    setList(
      list.map((item) => {
        if (item.id === id) {
          return {
            ...item,
            goods_count: count,
          }
        } else {
          return item
        }
      })
    )
  }

  useEffect(() => {
    const arr = JSON.parse(localStorage.getItem(LIST)) || []
    // 本地有就用本地的并同步到状态
    if (arr.length) {
      return setList(arr)
    }
    const getList = async () => {
      const r = await fetch('https://www.escook.cn/api/cart')
      const data = await r.json()
      setList(data.list)
    }
    getList()
  }, [])

  useEffect(() => {
    // list 变化的时候存一下
    localStorage.setItem(LIST, JSON.stringify(list))
  }, [list])

  return (
    <div className='app'>
      <MyHeader>购物车案例</MyHeader>
      {list.map((item) => (
        <GoodsItem
          key={item.id}
          {...item}
          changeStatus={changeStatus}
          changeCount={changeCount}
        />
      ))}
      <MyFooter list={list} changeAllStatus={changeAllStatus} />
    </div>
  )
}
